package com.our.sys.project1.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.our.set.web.UserSession;
import com.our.sys.common.utils.AppUtil;
import com.our.sys.project1.RunConstants;
import com.our.sys.project1.entity.Businesslicence;
import com.our.sys.project1.entity.HighValueMaterialDetail;
import com.our.sys.project1.entity.ReadyCode;
import com.our.sys.project1.entity.ReadySend;
import com.our.sys.project1.entity.Supplier;
import com.our.sys.project1.service.HighValueMaterialTypeService;
import com.our.sys.project1.service.LicensesService;
import com.our.sys.project1.service.ReadyCodeService;
import com.our.sys.project1.service.SupplierService;

@Controller
@RequestMapping("/ready_code")
public class ReadyCodeController {

    private static Logger logger = LoggerFactory.getLogger(ReadyCodeController.class);

    @Autowired
    private ReadyCodeService readyCodeService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private LicensesService licensesService;
    @Autowired
    private HighValueMaterialTypeService highValueMaterialTypeService;

    @RequestMapping(value = "/query")
    public @ResponseBody
    Map<String, Object> query(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Page<ReadyCode> page = new Page<ReadyCode>(request);
        String orderColumn = request.getParameter("sort");
        String dir = request.getParameter("dir");
        if (StringUtils.isBlank(orderColumn)) {
            page.setOrderBy("readyCodeTime");
            page.setOrder(Page.DESC);

        } else {
            page.setOrderBy(orderColumn);
            page.setOrder(dir);
        }

        List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
        String name = request.getParameter("name");
        if (StringUtils.isNotBlank(name)) {
            PropertyFilter filter = new PropertyFilter("LIKES_name_OR_materialName_OR_managerCode", name.trim());
            filters.add(filter);
        }

        Page<ReadyCode> data = readyCodeService.query(page, filters);
        for (ReadyCode rc : data.getResult()) {
            Supplier supplier = supplierService.queryById(rc.getSupplierId());
            Businesslicence bl = licensesService.findBBySupplierId(supplier.getId());
            HighValueMaterialDetail hmd = highValueMaterialTypeService.queryDById(rc.getMaterialId());
            rc.setSupplierName(supplier.getName());
            rc.setRegNo(bl.getRegisterNo());
            rc.setConsum(hmd.getConsum());
            rc.setMaterialName(hmd.getMaterialName());
            rc.setType(hmd.getType());
            rc.setUnit(hmd.getUnit());
            rc.setSpec(hmd.getSpec());
            rc.setName(hmd.getName());
            rc.setPrice(hmd.getPrice());
        }
        map = AppUtil.buildJSONDataResponse(data.getResult(), (long) data.getTotalCount());
        return map;
    }

    @RequestMapping(value = "/query_ready_code")
    public @ResponseBody
    Map<String, Object> queryReadyCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String name = request.getParameter("name");
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("1", RunConstants.READY_CODE);
        queryMap.put("2", name);
        List<ReadyCode> data = readyCodeService.queryList(queryMap);
        for (ReadyCode rc : data) {
            Supplier supplier = supplierService.queryById(rc.getSupplierId());
            Businesslicence bl = licensesService.findBBySupplierId(supplier.getId());
            HighValueMaterialDetail hmd = highValueMaterialTypeService.queryDById(rc.getMaterialId());
            rc.setSupplierName(supplier.getName());
            rc.setRegNo(bl.getRegisterNo());
            rc.setConsum(hmd.getConsum());
            rc.setMaterialName(hmd.getMaterialName());
            rc.setType(hmd.getType());
            rc.setUnit(hmd.getUnit());
            rc.setSpec(hmd.getSpec());
            rc.setName(hmd.getName());
            rc.setPrice(hmd.getPrice());
        }
        map = AppUtil.buildJSONDataResponse(data, (long) data.size());
        return map;
    }

    @RequestMapping(value = "/query_ready_code_edit")
    public @ResponseBody
    Map<String, Object> queryReadyCodeEdit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String name = request.getParameter("name");
        String readySendId = request.getParameter("readySendId");
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("1", RunConstants.READY_SEND);
        if (StringUtils.isNotBlank(name))
            queryMap.put("2", name);
        if (StringUtils.isNotBlank(readySendId))
            queryMap.put("3", Long.valueOf(readySendId));
        List<ReadyCode> data = readyCodeService.queryList(queryMap);
        for (ReadyCode rc : data) {
            Supplier supplier = supplierService.queryById(rc.getSupplierId());
            Businesslicence bl = licensesService.findBBySupplierId(supplier.getId());
            HighValueMaterialDetail hmd = highValueMaterialTypeService.queryDById(rc.getMaterialId());
            rc.setSupplierName(supplier.getName());
            rc.setRegNo(bl.getRegisterNo());
            rc.setConsum(hmd.getConsum());
            rc.setMaterialName(hmd.getMaterialName());
            rc.setType(hmd.getType());
            rc.setUnit(hmd.getUnit());
            rc.setSpec(hmd.getSpec());
            rc.setName(hmd.getName());
            if (null == rc.getPrice())
                rc.setPrice(hmd.getPrice());
        }
        map = AppUtil.buildJSONDataResponse(data, (long) data.size());
        return map;
    }

    @RequestMapping(value = "/query_ready_goods")
    public @ResponseBody
    Map<String, Object> queryReadyGoods(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Page<ReadyCode> page = new Page<ReadyCode>(request);
        String orderColumn = request.getParameter("sort");
        String dir = request.getParameter("dir");
        if (StringUtils.isBlank(orderColumn)) {
            page.setOrderBy("readyCodeTime");
            page.setOrder(Page.DESC);

        } else {
            page.setOrderBy(orderColumn);
            page.setOrder(dir);
        }

        List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
        String name = request.getParameter("name");
        if (StringUtils.isNotBlank(name)) {
            PropertyFilter filter = new PropertyFilter("LIKES_supplierName_OR_materialName_OR_factoryCode", name.trim());
            filters.add(filter);
        }

        PropertyFilter filter = new PropertyFilter("EQS_readyCodeState", RunConstants.READY_GOODS);
        filters.add(filter);

        Page<ReadyCode> data = readyCodeService.query(page, filters);
        for (ReadyCode rc : data.getResult()) {
            Supplier supplier = supplierService.queryById(rc.getSupplierId());
            Businesslicence bl = licensesService.findBBySupplierId(supplier.getId());
            HighValueMaterialDetail hmd = highValueMaterialTypeService.queryDById(rc.getMaterialId());
            rc.setSupplierName(supplier.getName());
            rc.setRegNo(bl.getRegisterNo());
            rc.setConsum(hmd.getConsum());
            rc.setMaterialName(hmd.getMaterialName());
            rc.setType(hmd.getType());
            rc.setUnit(hmd.getUnit());
            rc.setSpec(hmd.getSpec());
            rc.setName(hmd.getName());
            rc.setPrice(hmd.getPrice());
        }
        map = AppUtil.buildJSONDataResponse(data.getResult(), (long) data.getTotalCount());
        return map;
    }

    @RequestMapping(value = "/query_by_send")
    public @ResponseBody
    Map<String, Object> queryBySend(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Page<ReadyCode> page = new Page<ReadyCode>(request);
        String orderColumn = request.getParameter("sort");
        String dir = request.getParameter("dir");
        if (StringUtils.isBlank(orderColumn)) {
            page.setOrderBy("readyGoodsTime");
            page.setOrder(Page.DESC);

        } else {
            page.setOrderBy(orderColumn);
            page.setOrder(dir);
        }

        List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
        String readySendId = request.getParameter("readySendId");
        PropertyFilter filter = new PropertyFilter("EQL_readySendId", readySendId);
        filters.add(filter);

        Page<ReadyCode> data = readyCodeService.query(page, filters);
        for (ReadyCode rc : data.getResult()) {
            Supplier supplier = supplierService.queryById(rc.getSupplierId());
            Businesslicence bl = licensesService.findBBySupplierId(supplier.getId());
            HighValueMaterialDetail hmd = highValueMaterialTypeService.queryDById(rc.getMaterialId());
            rc.setSupplierName(supplier.getName());
            rc.setRegNo(bl.getRegisterNo());
            rc.setConsum(hmd.getConsum());
            rc.setMaterialName(hmd.getMaterialName());
            rc.setType(hmd.getType());
            rc.setUnit(hmd.getUnit());
            rc.setSpec(hmd.getSpec());
            rc.setName(hmd.getName());
            rc.setPrice(hmd.getPrice());
        }
        map = AppUtil.buildJSONDataResponse(data.getResult(), (long) data.getTotalCount());
        return map;
    }

    @RequestMapping(value = "/query_ready_send")
    public @ResponseBody
    Map<String, Object> queryReadySend(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Page<ReadySend> page = new Page<ReadySend>(request);
        String orderColumn = request.getParameter("sort");
        String dir = request.getParameter("dir");
        if (StringUtils.isBlank(orderColumn)) {
            page.setOrderBy("readySendTime");
            page.setOrder(Page.DESC);

        } else {
            page.setOrderBy(orderColumn);
            page.setOrder(dir);
        }

        List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
        String name = request.getParameter("name");
        if (StringUtils.isNotBlank(name)) {
            PropertyFilter filter = new PropertyFilter("LIKES_supplierName_OR_materialName_OR_factoryCode", name.trim());
            filters.add(filter);
        }
        String flag = request.getParameter("flag");
        PropertyFilter filter = new PropertyFilter("EQS_state", flag);
        filters.add(filter);

        Page<ReadySend> data = readyCodeService.querySend(page, filters);
        map = AppUtil.buildJSONDataResponse(data.getResult(), (long) data.getTotalCount());
        return map;
    }

    @RequestMapping(value = "/save")
    public @ResponseBody
    Map<String, Object> save(HttpServletRequest request, ReadyCode readyCode) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        UserSession u = (UserSession) request.getSession().getAttribute("userSession");
        try {
            readyCodeService.save(readyCode, u.getAccount());
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/print_code")
    public @ResponseBody
    Map<String, Object> printCode(HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String codes = request.getParameter("codes");
        String clazzPath = request.getSession().getServletContext().getRealPath("/resources/img/codeimg/");
        try {
            String html = readyCodeService.printCode(codes,clazzPath);
            map.put("success", true);
            map.put("html", html);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/re_ready")
    public @ResponseBody
    Map<String, Object> reReady(HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        UserSession u = (UserSession) request.getSession().getAttribute("userSession");
        String id = request.getParameter("id");
        String endTime = request.getParameter("endTime");
        try {
            readyCodeService.saveAg(Long.valueOf(id), endTime, u.getAccount());
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/cancel")
    public @ResponseBody
    Map<String, Object> delete(HttpServletRequest request, @RequestParam("id") String id) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        UserSession u = (UserSession) request.getSession().getAttribute("userSession");
        try {
            readyCodeService.cancel(Long.valueOf(id), u.getAccount());
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/ready_goods")
    public @ResponseBody
    Map<String, Object> readyGoods(HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String id = request.getParameter("id");
        String factoryCode = request.getParameter("factoryCode");
        UserSession u = (UserSession) request.getSession().getAttribute("userSession");
        try {
            readyCodeService.readyGoods(Long.valueOf(id), factoryCode, u.getAccount());
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/ready_send")
    public @ResponseBody
    Map<String, Object> readySend(HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String number = request.getParameter("number");
        UserSession u = (UserSession) request.getSession().getAttribute("userSession");
        String ids = request.getParameter("ids");
        String flag = request.getParameter("flag");
        String docName = request.getParameter("docName");
        String actionRoom = request.getParameter("actionRoom");
        String tofficesId = request.getParameter("tofficesId");
        String num = request.getParameter("num");
        try {
            readyCodeService.saveSend(number, ids, u.getAccount(), flag, docName, actionRoom, tofficesId, num);
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/ready_re_send")
    public @ResponseBody
    Map<String, Object> readyReSend(HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String number = request.getParameter("number");
        String rId = request.getParameter("rId");
        try {
            readyCodeService.saveReSend(number, Long.valueOf(rId));
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }
}
